<template>
	<div v-loading="loading" class="page-preview-container">
		<!-- 未有页面 -->

		<!-- 有激活页面 -->
		<div>
			<div class="box-title">{{ pageMode === 'preview' ? '页面预览' : '页面编辑' }}：{{ activePageInfo.name }}</div>
			<div class="phone-container" :style="activePageInfo.type === 'userCenter' ? 'background:#f7f7f7' : ''">
				<div v-if="!activePageInfo.id" class="empty-container">请先选择页面</div>
				<PhoneContainer v-else :page-mode="pageMode" :activePageInfoType="activePageInfo.type" />
			</div>
			<div v-if="activePageInfo.id">
				<div v-if="pageMode === 'preview'">
					<div class="btn-group flexRCC">
						<el-button type="primary" round size="mini" @click="editPage">编辑模块</el-button>
						<el-button type="info" round size="mini" plain @click="editConfig(activePageInfo.id)">基础配置</el-button>
						<el-button v-if="uniquePage.includes(activePageInfo.subType)" type="success" round size="mini" plain @click="usePage(activePageInfo)">设为使用</el-button>
						<el-button type="danger" round size="mini" plain @click="delPage(activePageInfo)">删除页面</el-button>
					</div>
				</div>
				<div v-if="pageMode === 'module'" class="btn-group flexRCC">
					<el-button type="info" round size="mini" plain @click="backPage">取消编辑</el-button>
					<el-button type="primary" round size="mini" plain @click="savePage">保存配置</el-button>
				</div>
			</div>
		</div>
		<!-- 组件 -->
		<DialogEditPageConfig ref="editPageConfig" />
	</div>
</template>

<script>
import { mapGetters } from 'vuex';
import { getPageData, editPageData } from '@/views/wxaBuildModule/api/page';
import pageEditConfig from '../mixin/pageEditConfig';
import PhoneContainer from './PhoneContainer';
import wxaBuildConfig from '@/views/wxaBuildModule/config';

export default {
	components: {
		PhoneContainer
	},
	mixins: [pageEditConfig],
	props: {
		activePageInfo: {
			type: Object
			// default: function () {
			//   return { id: null, name: "请先选择页面" };
			// },
		},
		pageMode: {
			type: String,
			default: null
		}
	},
	data() {
		return {
			// 配置
			// 状态
			loading: false,
			// 数据
			uniquePage: [],
			classifyCode: 'DEFAULT'
		};
	},
	watch: {
		activePageInfo(val) {
			if (val) this.getModules();
		}
	},
	computed: {
		...mapGetters(['activePageForm'])
	},
	created() {},
	mounted() {
		this.uniquePage = wxaBuildConfig[this.classifyCode].uniquePage;
	},
	methods: {
		/**
		 * 数据组
		 */
		// 获取页面数据
		getModules() {
			const params = {
				classifyCode: this.classifyCode,
				pageId: this.activePageInfo.id
			};
			if (!this.activePageInfo.id) {
				return;
			}
			this.loading = true;
			getPageData(params)
				.then(res => {
					const data = res.data;
					this.formatModulesToGet(data);
					data.activeModuleIndex = null;
					this.$store
						.dispatch('setActivePageForm', data)
						.then(() => {})
						.finally(() => {});
				})
				.catch(err => {})
				.finally(() => {
					this.loading = false;
				});
		},

		// 递归格式化数据
		formatModulesToGet(data) {
			data.modules = data.modules || [];
			data.modules.forEach(v => {
				if (v.biz) {
					v.biz.params = v.biz.params ? JSON.parse(v.biz.params) : '';
				}
				v.dump.featureParams = v.dump.featureParams ? JSON.parse(v.dump.featureParams) : '';
				v.dump.insideParams = v.dump.insideParams ? JSON.parse(v.dump.insideParams) : '';
				this.formatModulesToGet(v);
			});
		},

		/**
		 * 按钮组
		 */
		// 取消编辑
		backPage() {
			this.$emit('update:pageMode', 'preview');
			this.$bus.emit('wxaBuildModuleRefreshAsidePageList', {
				refreshActive: false
			});
		},

		// 保存编辑
savePage() {
      const params = {
        classifyCode: this.classifyCode
      }
      const data = JSON.parse(JSON.stringify(this.activePageForm))
      const intercept = data.modules.filter(item => ['kaikaquanyi'].includes(item.type))
      const guideFollow = data.modules.filter(item => ['guanzhugongzhonghao'].includes(item.type))
      const [kaikaquanyi = {}] = intercept
      const [guanzhugongzhonghao = {}] = guideFollow
      let new_params = {}
      let cloneParams = null
      if(intercept.length) {
        new_params = kaikaquanyi.biz?.params
        cloneParams = typeof new_params === 'string' ? JSON.parse(new_params) : new_params
      }


      if(intercept.length && !cloneParams?.ids.length) {
        return this.$message({ message: '开卡权益模块请添加内容',type: 'warning' })
      }

      if(guideFollow.length && guanzhugongzhonghao.biz.params) {
        new_params = guanzhugongzhonghao.biz?.params
        cloneParams = typeof new_params === 'string' ? JSON.parse(new_params) : new_params
      }

      if(guideFollow.length && guanzhugongzhonghao.biz.params && cloneParams.type === 1 && !guideFollow[0].pic) {
        return this.$message({ message: '关注公众号模块请上传二维码',type: 'warning' })
      }

      this.formatModulesToSave(data)
      this.loading = true
      editPageData({ data, params })
        .then((res) => {
          this.$notify({
            title: '成功',
            message: '保存页面成功',
            type: 'success',
            duration: 2000,
            offset: 40
          })
        })
        .catch((err) => {
        })
        .finally(() => {
          this.loading = false
        })
    },

		// 递归格式化数据
		formatModulesToSave(data) {
			const modules = data.modules || [];
			modules.forEach((v, i) => {
				v.ranking = i;
				if (v.biz) {
					v.biz.params = v.biz.params ? JSON.stringify(v.biz.params) : '';
				}
				v.dump.featureParams = v.dump.featureParams ? JSON.stringify(v.dump.featureParams) : '';
				v.dump.insideParams = v.dump.insideParams ? JSON.stringify(v.dump.insideParams) : '';
				this.formatModulesToSave(v);
			});
		}
		/**
		 * 状态组
		 */
		/**
		 * 方法组
		 */
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.page-preview-container {
	padding: 20px 0;

	.box-title {
		margin-bottom: 10px;
		text-align: center;
		color: #303133;
		font-weight: bold;
	}

	.empty-container {
		margin-top: 200px;
		text-align: center;
		color: #909399;
		font-style: 14px;
	}

	.phone-container {
		overflow: hidden;
		margin: 20px auto;
		width: 375px;
		height: 667px;
		padding: 5px 0;
		border-radius: 20px;
		box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
		background-color: #fff;
		// padding: 75px 20px 80px;
		// background: url("../../../../../assets/img/iphone_bg.png") no-repeat;
		background-size: 100% 100%;
	}
}
</style>
